<!-- 团购中心 -->
<template>
  <div>
    <el-header>
      <el-space wrap>
        <el-input
          style="width: 190px"
          v-model.trim="configReq.title"
          clearable
          placeholder="请输入商品名称"
        />
        <el-input
          style="width: 190px"
          v-model.trim="configReq.id"
          clearable
          placeholder="请输入商品ID"
        />
        <el-select v-model="configReq.status" clearable placeholder="请选择团购状态">
          <el-option
            v-for="item in options.status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" :icon="Search" @click="getInfo">查找</el-button>
        <el-button
          type="primary"
          :icon="Plus"
          @click="
            () => {
              drawerShow = true;
              title = '创建';
            }
          "
          v-btn="'product:groupshop:create'"
          >添加</el-button
        >
      </el-space>
    </el-header>
    <el-container>
      <!-- 列表 -->
      <el-table v-loading="loading" :data="infoTable" border>
        <el-table-column type="expand">
          <template #default="props">
            <el-descriptions border :column="1">
              <el-descriptions-item label="类目ID" width="150px">{{
                props.row.categoryId
              }}</el-descriptions-item>
              <el-descriptions-item>
                <el-table :data="props.row.groupShopSkuDTOList" border>
                  <el-table-column prop="skuId" label="SkuId" align="center" />
                  <el-table-column prop="title" label="规格标题" align="center" />
                  <el-table-column
                    prop="skuGroupShopPrice"
                    label="团购价格(元)"
                    align="center"
                  />
                  <el-table-column label="库存" align="center">
                    <template #default="item">
                      {{ item.row.stock + "(" + props.row.unit + ")" }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="originalPrice"
                    label="原始价格(元)"
                    align="center"
                  />
                  <el-table-column prop="price" label="售卖价格(元)" align="center" />
                  <el-table-column prop="vipPrice" label="会员价格(元)" align="center" />
                  <el-table-column prop="barCode" label="国际条码" align="center" />
                </el-table>
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="团购ID" align="center" width="90" />
        <el-table-column prop="spuId" label="商品ID" align="center" />
        <el-table-column prop="title" label="商品名称" align="center" width="150" />
        <el-table-column label="商品主图" align="center">
          <template #default="scope">
            <el-popover placement="right" :width="300" trigger="hover">
              <template #reference>
                <el-image style="height: 35px" :src="scope.row.img" />
              </template>
              <el-image style="width: 100%" :src="scope.row.img" />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="未满策略" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.automaticRefund ? 'success' : 'warning'">{{
              scope.row.automaticRefund ? "退款" : "发货"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="活动状态" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : ''">{{
              scope.row.status ? "进行" : "冻结"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center">
          <template #default="scope">
            {{ new Date(scope.row.gmtStart).formate("yyyy-MM-dd hh:mm") }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center">
          <template #default="scope">
            {{ new Date(scope.row.gmtEnd).formate("yyyy-MM-dd hh:mm") }}
          </template>
        </el-table-column>
        <el-table-column prop="buyerNum" label="当前人数" align="center" />
        <el-table-column prop="minNum" label="目标人数" align="center" />
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-space wrap v-if="!scope.row.status">
              <el-button
                type="primary"
                @click="editData(scope.row)"
                v-btn="'product:groupshop:edit'"
                >编辑</el-button
              >
              <el-button
                type="danger"
                @click="daleRow(scope.row.id)"
                v-btn="'product:groupshop:delete'"
                >删除</el-button
              >
            </el-space>
          </template>
        </el-table-column>
      </el-table>
      <!-- 抽屉部分 -->
      <el-drawer v-model="drawerShow" :show-close="false" direction="ltr" size="60%">
        <template #header>
          <p>{{ title }}团购商品</p>
          <el-button @click="drawerShow = false">取消</el-button>
          <el-button type="primary" @click="submitForm">{{ title }}</el-button>
        </template>
        <div>
          <h4>商品属性(spu)</h4>
          <el-form
            style="
              margin: 20px 0px;
              width: 100%;
              padding-left: 30px;
              box-sizing: border-box;
            "
            label-position="left"
            v-model="spuData"
            label-width="150px"
            status-icon
          >
            <el-form-item label="团购商品" prop="title">
              <el-cascader
                @change="changeSkuId"
                v-model="spuData.spuId"
                :props="props"
                placeholder="团购商品"
                :options="productList"
                :show-all-levels="false"
              />
            </el-form-item>
            <el-form-item label="团购时间" prop="title">
              <el-date-picker
                v-model="spuData.gmtStart"
                type="datetime"
                placeholder="选择日期"
                value-format="x"
              />
              <span style="margin: 0px 1rem">至</span>
              <el-date-picker
                v-model="spuData.gmtEnd"
                type="datetime"
                placeholder="选择日期"
                value-format="x"
              />
            </el-form-item>
            <el-form-item label="团购基础人数" prop="title">
              <el-input-number
                v-model="spuData.minNum"
                :min="1"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item label="活动结束时人数没有达到基础人数采取:" prop="title">
              <el-radio-group v-model="spuData.automaticRefund">
                <el-radio-button label="0">不退款,我要发货</el-radio-button>
                <el-radio-button label="1">自动退款,我不发货</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 30px 0px;
            "
          >
            <h4>商品类型(sku)</h4>
            <el-popover
              ref="popoverRef"
              placement="right"
              trigger="click"
              :width="300"
              @hide="newPriceAll = 1"
            >
              <el-form :label-width="100">
                <el-form-item label="团购价格">
                  <el-input-number
                    v-model="newPriceAll"
                    :min="1"
                    controls-position="right"
                  />元
                </el-form-item>
                <el-form-item>
                  <el-button @click="popoverRef.hide()">取消</el-button>
                  <el-button type="primary" @click="submitPrices">确定</el-button>
                </el-form-item>
              </el-form>
              <template #reference>
                <el-button type="primary" plain>批量定价</el-button>
              </template>
            </el-popover>
          </div>
          <el-table height="400" :data="skuList">
            <el-table-column prop="id" label="SkuId" align="center" />
            <el-table-column prop="barCode" label="Sku条形码" align="center" />
            <el-table-column prop="title" label="类型名" align="center" />
            <el-table-column prop="stock" label="库存" align="center" />
            <el-table-column prop="price" label="现价/元" align="center" />
            <el-table-column
              prop="skuGroupShopPrice"
              label="团购价格/元"
              align="center"
            />
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  @click="
                    () => {
                      Object.assign(skuGroupShopPriceObj, scope.row);
                      dialogFormVisible = true;
                    }
                  "
                  >更新</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 更新---对话框 -->
          <el-dialog
            v-model="dialogFormVisible"
            :destroy-on-close="true"
            width="450px"
            title="更新团购价格"
          >
            <el-form
              label-position="left"
              label-width="100px"
              status-icon
              class="dialog-form"
            >
              <el-form-item label="团购价格" style="width: 88%">
                <el-input-number
                  :min="1"
                  v-model="skuGroupShopPriceObj.skuGroupShopPrice"
                  controls-position="right"
                />
                元
              </el-form-item>
              <el-form-item label="现价" style="width: 88%">{{
                skuGroupShopPriceObj.price
              }}</el-form-item>
              <el-form-item label="sku类型名" style="width: 88%">{{
                skuGroupShopPriceObj.title
              }}</el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="updateConfirm">确认</el-button>
              </span>
            </template>
          </el-dialog>
        </div>
      </el-drawer>
    </el-container>
    <el-footer>
      <!-- 分页组件 -->
      <ElPagination
        :total="pageInfo.total"
        :limit="pageInfo.limit"
        @changeReq="changeConfig"
      ></ElPagination>
    </el-footer>
  </div>
</template>

<script setup lang="ts">
import { post } from "@/request/http";
import { Search, Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, watch } from "vue";
//数据部分
let loading = ref(false); //是否正在加载
let infoTable = ref([]); //主表格数据
let title = ref(""); //创建编辑的标题
let productList = ref([]); //商品树数据
let skuList = ref([]); // 对应商品数据的表格数据
let newPriceAll = ref(1); //团购新定价
let skuGroupShopPriceObj: any = reactive({}); //更新的行对象
let drawerShow = ref(false); // 是否显示抽屉
let dialogFormVisible = ref(false); //更新弹出框
let popoverRef = ref(); //ref
// 抽屉中要提交的信息
let spuData: any = reactive({
  _gp: "admin.groupshop",
  _mt: "",
  spuId: null,
  gmtStart: null, // 团购开始时间戳
  gmtEnd: null, //团购结束时间戳
  minNum: 1, //团购最低人数
  automaticRefund: 0, //团购人数未满是否自动退款
  groupShopSkuList: "", //团购sku链表
});
// 请求表格数据的配置
let configReq = reactive({
  _gp: "admin.groupshop",
  _mt: "list",
  pageNo: 1, //跳转页数
  limit: 20, //显示条数
  title: "",
  id: "",
  status: "",
});

// 传给分页组件的数据
let pageInfo = reactive({
  page: 1, //跳转页数
  limit: 20, //显示条数
  total: 0,
});
// 选择器数据
let options = reactive({
  status: [
    { value: 0, label: "冻结" },
    { value: 1, label: "活动" },
  ],
});
// 商品级联选择器的配置
let props = reactive({
  label: "label",
  children: "children",
  value: "id",
  emitPath: false,
});

//函数部分
const getInfo = () => {
  loading.value = true;
  post(configReq).then((res) => {
    if (200 == res?.errno) {
      //成功状态码
      const { items, total } = res.data;
      infoTable.value = items; //获取表格信息
      pageInfo.total = total; //获取总条数
      loading.value = false; //加载完毕
    }
  });
};
// 分页切换触发
const changeConfig = (e: { page: number; limit: number }) => {
  Object.assign(configReq, { limit: e.limit, pageNo: e.page });
  getInfo();
};
// 删除行
const daleRow = (id: number) => {
  ElMessageBox.confirm("是否删除团购商品?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      post({ _gp: "admin.groupshop", _mt: "delete", id }).then((res) => {
        if (200 == res?.errno) {
          //成功状态码
          ElMessage.success("删除成功");
          getInfo(); //更新数据
        }
      });
    })
    .catch(() => {
      ElMessage.info("删除取消");
    });
};
// 获取商品树数据的方法
const getTree = () => {
  post({ _gp: "admin.product", _mt: "getSpuBigTree" }).then((res) => {
    if (200 == res?.errno) {
      //成功状态码
      productList.value = res.data;
    }
  });
};
// 获取抽屉对应商品表格数据的方法
const getDetail = (spuId: number) => {
  post({ _gp: "admin.product", _mt: "detail", spuId }).then((res) => {
    if (200 == res?.errno) {
      //成功状态码
      skuList.value = res.data.skuList;
      return;
    }
    skuList.value = []; //清空抽屉表格
  });
};
// 改变商品时获取表格
const changeSkuId = () => {
  if (spuData.spuId) {
    getDetail(spuData.spuId);
  } else {
    //当改变选中商品时加载对应的表格,如果为空清空表格
    skuList.value = [];
  }
};
// 修改全部团购价格
const submitPrices = () => {
  skuList.value.forEach((item: any) => {
    item.skuGroupShopPrice = newPriceAll.value;
  });
  popoverRef.value.hide();
};
// 修改行价格
const updateConfirm = () => {
  let { id, skuGroupShopPrice } = skuGroupShopPriceObj;
  skuList.value.forEach((item: any) => {
    if (item.id == id) {
      item.skuGroupShopPrice = skuGroupShopPrice;
    }
  });
  dialogFormVisible.value = false;
};
// 点击编辑后
const editData = (row: any) => {
  let { spuId, gmtStart, gmtEnd, minNum, automaticRefund, groupShopSkuDTOList, id } = row;
  Object.assign(spuData, {
    spuId,
    gmtStart,
    gmtEnd,
    minNum,
    automaticRefund,
    id,
  });
  skuList.value = JSON.parse(JSON.stringify(groupShopSkuDTOList));
  drawerShow.value = true;
  title.value = "编辑";
};
// 重置表单数据
const resetData = () => {
  Object.assign(spuData, {
    _gp: "admin.groupshop",
    _mt: "",
    spuId: null,
    gmtStart: null, // 团购开始时间戳
    gmtEnd: null, //团购结束时间戳
    minNum: 1, //团购最低人数
    automaticRefund: 1, //团购人数未满是否自动退款
    groupShopSkuList: "", //团购sku链表
  });
  newPriceAll.value = 1;
  skuList.value = []; //清空表格
};
// 提交数据
const submitForm = () => {
  console.log(skuList.value);

  let groupShopSkuList = skuList.value.map((item: any) => {
    return { skuId: item.id, skuGroupShopPrice: item.skuGroupShopPrice };
  }); //获取sku
  let data = { ...spuData };
  data._mt = title.value == "创建" ? "create" : "edit"; //判断是编辑还是添加
  data.groupShopSkuList = JSON.stringify(groupShopSkuList);
  post(data).then((res) => {
    if (200 == res?.errno) {
      ElMessage.success(title.value + "成功");
      getInfo(); //刷新数据
      drawerShow.value = false;
    }
  });
};
onMounted(() => {
  getInfo();
});
watch(drawerShow, (n) => {
  if (!n) resetData(); //在关闭弹窗时重置数据
  if (productList.value.length != 0) return; //长度不为0时获取树
  if (n) getTree(); //获取商品树数据
});
</script>

<style scoped lang="less">
.el-header {
  height: auto;
  margin-bottom: 20px;
}
.dialog-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
</style>
